const express = require('express');
const router = express.Router();
const { Favorite } = require('../models');
const { Op } = require('sequelize');
const jwt = require('jsonwebtoken');
const JWT_SECRET = process.env.JWT_SECRET;
const { getSignedUrl } = require("../utils/oss"); // 确保你已经正确引入签名工具

// 收藏/取消收藏（切换）
router.post('/toggle', async (req, res) => {
    const { itemId } = req.body;

    console.log('[favorite] 切换请求:', { itemId });

    if (!itemId) {
        return res.status(400).json({ code: 400, message: 'userId 和 itemId 不能为空' });
    }
    // 从请求头中获取 token
    const authHeader = req.headers.authorization || req.headers.token;
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
        console.warn('[auth] 缺少 token');
        return fail(res, '未提供 token', 401);
    }
    const token = authHeader.split(' ')[1];
    let payload;

    payload = jwt.verify(token, JWT_SECRET);
    const { userId } = payload;
    try {
        const favorite = await Favorite.findOne({
            where: { userId, itemId },
            paranoid: false // 包括软删除的记录
        });

        // 如果存在收藏记录
        if (favorite) {
            if (favorite.deletedAt) {
                // 是已删除状态（软删除） -> 恢复
                await favorite.restore();
                console.log('[favorite] 恢复收藏:', favorite.toJSON());
                return res.json({ code: 200, message: '收藏成功', data: { isFavorite: true } });
            } else {
                // 正常收藏状态 -> 执行删除
                await favorite.destroy();
                console.log('[favorite] 取消收藏:', favorite.toJSON());
                return res.json({ code: 200, message: '取消收藏成功', data: { isFavorite: false } });
            }
        }

        // 新增收藏
        const newFavorite = await Favorite.create({ userId, itemId });
        console.log('[favorite] 新建收藏:', newFavorite.toJSON());
        res.json({ code: 200, message: '收藏成功', data: { isFavorite: true } });

    } catch (err) {
        console.error('[favorite] 切换失败:', err);
        res.status(500).json({ code: 500, message: '收藏操作失败', error: err.message });
    }
});
// 查询我的收藏列表（分类筛选）
router.post('/my-list', async (req, res) => {
    const { page = 1, pageSize = 10, categoryId } = req.body;

    const offset = (page - 1) * pageSize;

    // 解析 token 获取 userId
    const authHeader = req.headers.authorization || req.headers.token;
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
        return res.status(401).json({ code: 401, message: '未提供 token' });
    }

    let userId;
    try {
        const token = authHeader.split(' ')[1];
        const payload = jwt.verify(token, JWT_SECRET);
        userId = payload.userId;
    } catch (err) {
        console.error('[favorite] token 解析失败:', err.message);
        return res.status(401).json({ code: 401, message: 'token 无效或已过期' });
    }
    try {
        const { Item } = require('../models');

        // 收藏记录中关联出商品
        const { count, rows } = await Favorite.findAndCountAll({
            where: { userId },
            include: [
                {
                    model: Item,
                    as: 'favoritedItem',
                    where: {
                        ...(categoryId ? { categoryId } : {}),
                        status: 1
                    },
                    required: true
                }
            ],
            limit: Number(pageSize),
            offset: Number(offset),
            order: [['createdAt', 'DESC']]
        });
        // 给每条商品数据的 image_urls 添加签名
        const signedList = rows.map(item => {
            const data = item.toJSON();

            if (Array.isArray(data.image_urls)) {
                data.signed_image_urls = data.image_urls.map(key => {
                    try {
                        return getSignedUrl(key);
                    } catch (err) {
                        console.error('[item] 生成签名失败:', key, err);
                        return null;
                    }
                });
            } else {
                data.signed_image_urls = [];
            }

            return data;
        });
        // 格式化返回
        const list = rows.map(fav => {
            const item = fav.favoritedItem?.toJSON?.() || {};
            item.isFavorite = true;

            if (Array.isArray(item.image_urls)) {
                item.signed_image_urls = item.image_urls.map(key => {
                    try {
                        return getSignedUrl(key);
                    } catch (err) {
                        console.error('[item] 生成签名失败:', key, err);
                        return null;
                    }
                });
            } else {
                item.signed_image_urls = [];
            }

            return item;
        });

        return res.json({
            code: 200,
            message: '获取成功',
            data: {
                total: count,
                list
            }
        });

    } catch (err) {
        console.error('[favorite] 获取收藏列表失败:', err);
        return res.status(500).json({ code: 500, message: '服务器错误', error: err.message });
    }
});

module.exports = router;